package com.ljfiction.book.activitys;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.geetest.sdk.Bind.GT3GeetestBindListener;
import com.geetest.sdk.Bind.GT3GeetestUtilsBind;
import com.google.gson.Gson;
import com.ljfiction.book.Dialog.ImageDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.Md5;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserBean;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.PreferencesTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;

public class RetriveNextActivity extends BaseActivity {

    @BindView(R.id.back_retrivenext)
    ImageView backRetrivenext;
    @BindView(R.id.touxiang)
    CircularImageView touxiang;
    @BindView(R.id.womentext)
    TextView womentext;
    @BindView(R.id.zhucewumen)
    LinearLayout zhucewumen;
    @BindView(R.id.mantext)
    TextView mantext;
    @BindView(R.id.zhucemen)
    LinearLayout zhucemen;
    @BindView(R.id.zhecename)
    ContainsEmojiEditText zhecename;
    @BindView(R.id.zhuceok)
    SuperButton zhuceok;
    @BindView(R.id.zhucewumenimage)
    ImageView zhucewumenimage;
    @BindView(R.id.menimage)
    ImageView menimage;

    private String iswomen = "1";
    private ImageDialog imageDialog;
    private NoBackgLodDialog loadingDialog;
    private String yanzhengma, mima, phone, quhao;
    private boolean isImage = false;//是否上传图片
    /*  *//**
     * api1，需替换成自己的服务器URL
     */
    private static final String captchaURL = HttpManager.IP+"/verification/person-ExtremeTestCode";
    /**
     * api2，需替换成自己的服务器URL
     */
    private static final String validateURL = HttpManager.IP + "/person-regInfo";
    private GT3GeetestUtilsBind gt3GeetestUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrive_next);
        ButterKnife.bind(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        yanzhengma = getIntent().getStringExtra("yanzhengma");
        mima = getIntent().getStringExtra("mima");
        phone = getIntent().getStringExtra("phone");
        quhao = getIntent().getStringExtra("quhao");
        init();
    }
    /**
     * 务必在oncreate里初始化
     */
    private void init() {
        gt3GeetestUtils = new GT3GeetestUtilsBind(this);
        // 设置debug模式，开代理抓包可使用，默认关闭，TODO 生产环境务必设置为false
        gt3GeetestUtils.setDebug(false);
        // 设置加载webview超时时间，单位毫秒，默认15000，仅且webview加载静态文件超时，不包括之前的http请求
        gt3GeetestUtils.setTimeout(15000);
        // 设置webview请求超时(用户点选或滑动完成，前端请求后端接口)，单位毫秒，默认10000
        gt3GeetestUtils.setWebviewTimeout(10000);
        /**
         * 点击调起验证
         */

    }
    @OnClick({R.id.back_retrivenext, R.id.touxiang, R.id.zhucewumen, R.id.zhucemen, R.id.zhuceok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_retrivenext:
                goBack();
                break;
            case R.id.touxiang:
                imageDialog = new ImageDialog(this, "logoName.jpg", new ImageDialog.Listener() {
                    @Override
                    public void getImage(Bitmap photo) {
                        touxiang.setImageBitmap(photo);
                        isImage = true;
                    }

                });
                break;
            case R.id.zhucewumen:
                womentext.setTextColor(Color.parseColor("#fb5e6f"));
                mantext.setTextColor(Color.parseColor("#999999"));
                iswomen = "1";
                zhucewumenimage.setImageResource(R.mipmap.women);
                menimage.setImageResource(R.mipmap.m);
                break;
            case R.id.zhucemen:
                zhucewumenimage.setImageResource(R.mipmap.w);
                menimage.setImageResource(R.mipmap.men);
                mantext.setTextColor(Color.parseColor("#fb5e6f"));
                womentext.setTextColor(Color.parseColor("#999999"));
                iswomen = "0";

                break;

            case R.id.zhuceok:
                if (zhecename.getText().toString().equals("")) {
                    showToast("亲，昵称不能为空哦！");
                } else if (!StringTool.verifyUserName(zhecename.getText().toString())) {
                    showToast("昵称只支持汉字、字母、数字和下划线");
                } else if (zhecename.getText().toString().length() > 7) {
                    showToast("亲，昵称不能超过7个字哦！");
                } else {
                    toYanzhengName();
                }
                break;
        }
    }



    private void toYanzhengName() {
        OkHttpUtils.get(HttpManager.IP + "/person-checkNickName/" + zhecename.getText().toString())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(RetriveNextActivity.this, true);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (loadingDialog!=null){
                            loadingDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                startCustomVerify();

                            } else {
                                showToast(jsonObject.getString("msg"));
                            }


                        } catch (JSONException e) {
                            loadingDialog.dismis();
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void  toZhuce(String one,String tow,String three) {

        OkHttpUtils.post(HttpManager.IP + "/person-regInfo")
                .params("fn_geetest_challenge",one)
                .params("fn_geetest_validate",tow )
                .params("fn_geetest_seccode", three)
                .params("client_type","native")
                .params("code", yanzhengma)
                .params("pseudonym", zhecename.getText().toString())
                .params("userCode", StringTool.getChannelName(RetriveNextActivity.this))
                .params("terminal", "2")
                .params("userPassword", Md5.encryption(mima))
                .params("userSex", iswomen)
                .params("userPhone", quhao.replace("+", "") + "+" + phone)
                .execute(new StringCallback() {



                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                gt3GeetestUtils.gt3TestFinish();
                                if (isImage) {
                                    creatUserImage(String.valueOf(jsonObject.getInt("data")));
                                }

                                tologin();
                            }else {
                                gt3GeetestUtils.gt3TestClose();
                            }
                                showToast(jsonObject.getString("msg"));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void tologin() {
        OkHttpUtils.post(HttpManager.IP + "/person-login")
                .params("userName", phone)
                .params("userPassword", Md5.encryption(mima))
                .params("terminal", "2")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(RetriveNextActivity.this, true);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (loadingDialog != null) {
                            loadingDialog.dismis();
                        }
                        Gson gson = new Gson();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                enjoin(user);
                                if (user.getsTR() == 1) {
                                    Tool.xmjaddtishi(RetriveNextActivity.this);
                                    UserManageBean.userBean.setsTR(0);
                                } else {
                                    showToast("登陆成功");
                                }
                            } else {
                                showToast(jsonObject.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void enjoin(UserBean user) {
        PreferencesTool.saveLoginInfo(this, phone, mima);
        SettingManager.getInstance().savesessionId(user.getToken());
        PreferencesTool.saveValue(this, "userId", user.getUserId() + "");
        PreferencesTool.saveValue(this, "isCache", "1");
        PreferencesTool.saveValue(this, "isChecked", "1");
        UserManageBean.userBean = user;
        UserManageBean.setIsLogin(true);
        setResult(1);
        goBack();

    }

    private void creatUserImage(String userId) {
        OkHttpUtils.post(HttpManager.IP + "/userRegisterHeadImgUpload")
                .params("userId", userId)
                .params("file", new File(getExternalCacheDir() + "/logoName.jpg"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                            } else {
                                showToast("图片上传失败，请在编辑中修改");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            imageDialog.onActivityResult(data, requestCode, 1);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 开始验证 TODO 自定义api1及自定义api2示例
     */
    private void startCustomVerify() {
        // 开启LoadDialog 第二个参数为lang（语言，如果为null则为系统语言）
        gt3GeetestUtils.showLoadingDialog(this, "china");
        // 设置是否可以点击Dialog灰色区域关闭验证码
        gt3GeetestUtils.setDialogTouch(false);
        OkHttpUtils.post(captchaURL)
                .params("client_type","native")
                .params("phoneId",quhao.replace("+", "") + "+" +phone)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                String ss = jsonObject.getString("data");
                                continueVerify(new JSONObject(ss));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        //  new RequestAPI1().execute();
    }


    /**
     * 开始验证 TODO 自定义api1及自定义api2示例
     */
    private void continueVerify(JSONObject parmas) {
        // parmas格式"{\"success\":1,\"challenge\":\"4a5cef77243baa51b2090f7258bf1368\",\"gt\":\"019924a82c70bb123aae90d483087f94\",\"new_captcha\":true}"
        // 设置api请求结果
        gt3GeetestUtils.gtSetApi1Json(parmas);
        gt3GeetestUtils.getGeetest(this, captchaURL, validateURL, null, new GT3GeetestBindListener() {

            /**
             * @param num 1: 点击验证码的关闭按钮, 2: 点击屏幕关闭验证码, 3: 点击返回键关闭验证码
             */
            @Override
            public void gt3CloseDialog(int num) {

            }

            /**
             * 为API1接口添加数据，数据拼接在URL后，API1接口默认get请求
             */
            @Override
            public Map<String, String> gt3CaptchaApi1() {

                Map<String, String> map = new HashMap<String, String>();
                map.put("time", "" + System.currentTimeMillis());
                return map;
            }

            /**
             * api1接口返回数据
             */
            @Override
            public void gt3FirstResult(JSONObject jsonObject) {

            }


            /**
             * 准备完成，即将弹出验证码
             */
            @Override
            public void gt3DialogReady() {

            }

            /**
             * 数据统计，从开启验证到成功加载验证码结束，具体解释详见GitHub文档
             */
            @Override
            public void gt3GeetestStatisticsJson(JSONObject jsonObject) {

            }

            /**
             * 返回是否自定义api2，true为自定义api2
             * false： gt3GetDialogResult(String result)，返回api2需要参数
             * true： gt3GetDialogResult(boolean a, String result)，返回api2需要的参数
             */
            @Override
            public boolean gt3SetIsCustom() {

                return true;
            }

            /**
             * 用户滑动或点选完成后触发，gt3SetIsCustom配置为false才走此接口
             *
             * @param result api2接口需要参数
             */
            @Override
            public void gt3GetDialogResult(String result) {

            }

            /**
             * 用户滑动或点选完成后触发，gt3SetIsCustom配置为true才走此接口
             *
             * @param status 验证是否成功
             * @param result api2接口需要参数
             */
            @Override
            public void gt3GetDialogResult(boolean status, String result) {
                //Log.i(TAG, "gt3DialogSuccessResult-->" + result);
                if (status) {
                    try {
                        // 1.取出该接口返回的三个参数用于自定义二次验证
                        JSONObject jsonObject = new JSONObject(result);
                        toZhuce( jsonObject.getString("geetest_challenge"),jsonObject.getString("geetest_validate"),jsonObject.getString("geetest_seccode"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    gt3GeetestUtils.gt3TestClose();
                }
            }

            /**
             * 为API2接口添加数据，数据拼接在URL后，API2接口默认get请求
             * 默认已有数据：geetest_challenge，geetest_validate，geetest_seccode
             * TODO 注意： 切勿重复添加以上数据
             */
            @Override
            public Map<String, String> gt3SecondResult() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("test", "test");
                return map;
            }

            /**
             * api2完成回调，判断是否验证成功，且成功调用gt3TestFinish，失败调用gt3TestClose
             *
             * @param result api2接口返回数据
             */
            @Override
            public void gt3DialogSuccessResult(String result) {

            }

            /**
             * @param error 返回错误码，具体解释见GitHub文档
             */
            @Override
            public void gt3DialogOnError(String error) {
                // Log.i(TAG, "gt3DialogOnError-->" + error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /**
         * TODO 务必调用
         * 页面关闭时释放资源
         */
        gt3GeetestUtils.cancelUtils();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /**
         * 横竖屏切换适配
         */
        gt3GeetestUtils.changeDialogLayout();
    }
}
